package com.py.credit.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.py.credit.service.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.py.credit.common.XypjConstants;
import com.py.credit.entity.EvalInfo;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.core.utils.BeanUtil;
import com.py.framework.core.utils.DateUtils;

/**
 * 信用评价前台网站用户设置Controller
 */
@RestController
@RequestMapping("/xypj/gateway")
public class GatewayUserController extends GatewaySystemController {

	@Autowired
	private GatewayUserService gatewayUserService;

	@Autowired
	private GatewayAuthenticationService gatewayAuthenticationService;

	@Autowired
	private EvalInfoService evalInfoService;
	@Autowired
	private CardsService cardsService;
	@Autowired
	private XypjRemoteBaseService xypjRemoteBaseService;

	@Value("${absolutepath}")
	private String absolutepath;

	/**
	 * 获取用户信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getCurrentXypjUser.json", method = RequestMethod.POST)
	public RestServiceResult<Map<String, Object>> getCurrentXypjUser(HttpServletRequest request) {
		Map<String, Object> result = new HashMap<>();
		String token = HttpServletHelper.getUserXypjGatewayToken(request);
		if (StringUtils.isNotBlank(token)) {
			try {
				// 用户信息
				GatewayUserEntity user = gatewayAuthenticationService.getCurrentUserInfo(token);
				if (null != user && user.getId() > XypjConstants.NUMBER_ZERO) {
					// 用户添加信用分
					EvalInfo evalInfo = evalInfoService.getNewEvalInfo(user.getId() + "");

					if (null != evalInfo) {
						user.setCreditScore(evalInfo.getScore());
						user.setCreditRank(evalInfo.getRank());
					}

					result.putAll(BeanUtil.populateBean2Map(user));
					result.remove("password");
				}
			} catch (Exception e) {
				ExceptionLogger.error(e);
			}
		}
		return super.getSuccessRestServiceResult(result);
	}

	/**
	 * 获取通知公告数据（top5）
	 *
	 * @return
	 */
	@RequestMapping(value = "/getXypjNotice.json", method = RequestMethod.POST)
	public RestServiceResult getXypjNotice(HttpServletRequest request) {
		String token = HttpServletHelper.getUserXypjGatewayToken(request);

		if (StringUtils.isBlank(token)) {
			return super.getFailedRestServiceResult("未获取到当前用户信息！");
		}

		try {
			// 用户信息
			GatewayUserEntity user = gatewayAuthenticationService.getCurrentUserInfo(token);
			if (null != user && user.getId() > XypjConstants.NUMBER_ZERO) {
				return super.getSuccessRestServiceResult(gatewayUserService.getXypjNotice(user.getId()));
			} else {
				return super.getFailedRestServiceResult("未获取到当前用户信息！");
			}
		} catch (Exception e) {
			ExceptionLogger.error("GatewayUserController#getXypjNotice", "未获取到当前用户信息！");
			return super.getFailedRestServiceResult("未获取到当前用户信息！");
		}
	}

	/**
	 * 编辑资料
	 *
	 * @param id
	 *            用户id
	 * @param password
	 *            原始密码
	 * @param newPassword
	 *            新密码
	 * @param sjhm
	 *            手机号码
	 * @param dzyx
	 *            电子邮箱
	 * @return
	 */
	@RequestMapping(value = "/modifyUserInfo.json", method = RequestMethod.POST)
	public RestServiceResult modifyUserInfo(@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "password", defaultValue = "", required = true) String password,
			@RequestParam(value = "newPassword", defaultValue = "", required = true) String newPassword,
			@RequestParam(value = "sjhm", defaultValue = "", required = true) String sjhm,
			@RequestParam(value = "dzyx", defaultValue = "", required = true) String dzyx, HttpServletRequest request) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", Long.parseLong(id));
		GatewayUserEntity gatewayUserEntity = gatewayUserService.getUserByTwoPrincipal(params);

		String xypjGatewayToken = HttpServletHelper.getUserXypjGatewayToken(request);

		// 校验原密码
		if (null != newPassword && !"".equals(newPassword)) {
			if (!gatewayUserEntity.getPassword().equals(password)) {
				return super.getFailedRestServiceResult("原始密码不正确！");
			}

			if(password.equals(newPassword)) {
				return super.getFailedRestServiceResult("新密码和原始密码一致，修改失败！");
			}
			params.put("newPassword", newPassword);
			gatewayUserService.modifyUserInfo(params);

			// 清除用户缓存
			if (StringUtils.isNotBlank(xypjGatewayToken)) {
				try {
					gatewayAuthenticationService.clearUserSessionData(xypjGatewayToken, gatewayUserEntity);
				} catch (Exception e) {
					ExceptionLogger.error(e);
				}
			}
		} else {
			params.put("sjhm", sjhm);
			params.put("dzyx", dzyx);
			gatewayUserService.modifyUserInfo(params);

			gatewayUserEntity.setSjhm("".equals(sjhm) ? gatewayUserEntity.getSjhm() : sjhm);
			gatewayUserEntity.setDzyx("".equals(dzyx) ? gatewayUserEntity.getDzyx() : dzyx);

			// 刷新用户缓存
			if (StringUtils.isNotBlank(xypjGatewayToken)) {
				try {
					gatewayAuthenticationService.putUserSessionData(xypjGatewayToken, gatewayUserEntity);
				} catch (Exception e) {
					ExceptionLogger.error(e);
				}
			}
		}

		return super.getSuccessRestServiceResult();
	}
	
	/**实名认证
	 * 
	 * @param ztmc 主体名称
	 * @param bm 编码
	 * @param id 
	 * @param fddbr 法定代表人
	 * @param zjwj 
	 * @param sfzwjFront
	 * @param sfzwjBack
	 * @param type 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/repeatModifyUserInfo.json", method = RequestMethod.POST)
	public RestServiceResult<Object> repeatModifyUserInfo(String ztmc, String bm, String id, String fddbr,
			MultipartFile zjwj, MultipartFile sfzwjFront, MultipartFile sfzwjBack, String type,
			HttpServletRequest request) {
		RestServiceResult<Object> r = new RestServiceResult<>();
		Map<String, Object> params = new HashMap<>();
		params.put("id", Long.parseLong(id));
		// String tybm = (String) xypjRemoteBaseService.checkZmtcIsExist(ztmc, bm,
		// type).getData();
		// if (null == tybm || tybm.equals("")) {
		//
		// return super.getFailedRestServiceResult("该信用主体不存在");
		//
		// }
		if (type.equals("C")) {
			if (null == zjwj) {
				return super.getFailedRestServiceResult("请选择营业执照");
			}

			if (!zjwj.getOriginalFilename().toLowerCase().endsWith(".png")
					&& !zjwj.getOriginalFilename().toLowerCase().endsWith(".jpeg")
					&& !zjwj.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
				return super.getFailedRestServiceResult("营业执照仅支持jpg,jpeg,png格式");
			}

			if (zjwj.getSize() > 5 * 1024 * 1024) {
				return super.getFailedRestServiceResult("营业执照大小超过5M");
			}
		}

		if (null == sfzwjFront) {
			return super.getFailedRestServiceResult("请选择身份证正面");
		}

		if (!sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".png")
				&& !sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".jpeg")
				&& !sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
			return super.getFailedRestServiceResult("身份证正面仅支持jpg,jpeg,png格式");
		}

		if (sfzwjFront.getSize() > 5 * 1024 * 1024) {
			return super.getFailedRestServiceResult("身份证正面大小超过5M");
		}

		if (null == sfzwjBack) {
			return super.getFailedRestServiceResult("请选择身份证反面");
		}

		if (!sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".png")
				&& !sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".jpeg")
				&& !sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
			return super.getFailedRestServiceResult("身份证反面仅支持jpg,jpeg,png格式");
		}

		if (sfzwjBack.getSize() > 5 * 1024 * 1024) {
			return super.getFailedRestServiceResult("身份证反面大小超过5M");
		}
		try {

			// 拼装成GatewayUserEntity实体类
			GatewayUserEntity entity = new GatewayUserEntity();
			entity.setBm(bm);
			entity.setFddbr(fddbr);
			entity.setZtmc(ztmc);
			entity.setId(Long.parseLong(id));
			entity.setType(type);
			if (null != entity) {
				Timestamp currentTime = new Timestamp(DateUtils.getCurrentDateTime().getTime());
				entity.setUpdateTime(currentTime);

				// 先把文件存到本地,生成一个uuid序列号文件夹
				String dirPath = absolutepath + File.separator + "xypjUser" + File.separator
						+ UuidUtil.getInstance().getUUid();
				entity.setDirPath(dirPath);

				// 存储文件
				if (entity.getType().equals("C")) {
					gatewayUserService.fileUpload(zjwj, dirPath, "zjwj_");
					entity.setZjwj("zjwj_" + zjwj.getOriginalFilename());
				}

				gatewayUserService.fileUpload(sfzwjFront, dirPath, "sfzfront_");
				entity.setSfzwj_front("sfzfront_" + sfzwjFront.getOriginalFilename());
				gatewayUserService.fileUpload(sfzwjBack, dirPath, "sfzback_");
				entity.setSfzwj_back("sfzback_" + sfzwjBack.getOriginalFilename());

				entity.setShzt("S");
				entity.setZhzt("J");
			}

			gatewayUserService.repeatModifyUserInfo(entity);
			List<String> list = new ArrayList<>();
			if(entity.getType().equals("C")) {
				String[]	Cardstype = { "ZZ", "SF", "SS" };
				for (int i = 0; i < Cardstype.length; i++) {
					List<String> list1 = cardsService.selectCardIdByUserId(id, Cardstype[i]);
					list.add(list1.get(0));
				}
			}
			if(!entity.getType().equals("C")) {
				String[] Cardstype = {"SF", "SS" };
				for (int i = 0; i < Cardstype.length; i++) {
					List<String> list1 = cardsService.selectCardIdByUserId(id, Cardstype[i]);
					list.add(list1.get(0));
				}
			}
			StringBuilder sb1 = new StringBuilder();
			sb1.append(entity.getDirPath()).append(File.separator).append(entity.getZjwj());
			StringBuilder sb2 = new StringBuilder();
			sb2.append(entity.getDirPath()).append(File.separator).append(entity.getSfzwj_back());
			StringBuilder sb3 = new StringBuilder();
			sb3.append(entity.getDirPath()).append(File.separator).append(entity.getSfzwj_front());
			String[] sb = { sb1.toString(), sb2.toString(), sb3.toString() };
			int size = list.size();
			for (int i = 0; i < size; i++) {
				gatewayUserService.modifyZjPhotoInfo(null, null, null, sb[i], null, null, Long.parseLong(list.get(i)),
						null);
			}
		} catch (Exception e) {
			r.setCode(RestServiceResult.CODE_UNKNOW);
			r.setMsg("实名认证失败！");
		}

		String xypjGatewayToken = HttpServletHelper.getUserXypjGatewayToken(request);
		 // 清除用户缓存
        if (StringUtils.isNotBlank(xypjGatewayToken)) {
            try {
                gatewayAuthenticationService.clearUserSessionData(xypjGatewayToken, gatewayAuthenticationService.getCurrentUserInfo(xypjGatewayToken));
            } catch (Exception e) {
                ExceptionLogger.error(e);
            }
        }
		return r;
	}

	/**
	 * 上传头像
	 *
	 * @param id
	 *            用户id
	 * @param icon
	 *            头像图片
	 * @return
	 */
	@RequestMapping(value = "/uploadUserIcon.json", method = RequestMethod.POST)
	public RestServiceResult uploadUserIcon(@RequestParam(value = "id", defaultValue = "", required = true) String id,
			MultipartFile icon, HttpServletRequest request) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", Long.parseLong(id));
		GatewayUserEntity gatewayUserEntity = gatewayUserService.getUserByTwoPrincipal(params);

		String xypjGatewayToken = HttpServletHelper.getUserXypjGatewayToken(request);

		// 上传头像
		String iconPath = "";
		if (null != icon) {
			if (!icon.getOriginalFilename().toLowerCase().endsWith(".png")
					&& !icon.getOriginalFilename().toLowerCase().endsWith(".jpeg")
					&& !icon.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
				return super.getFailedRestServiceResult("头像仅支持jpg,jpeg,png格式");
			}

			if (icon.getSize() > 1 * 1024 * 1024) {
				return super.getFailedRestServiceResult("头像大小超过1M");
			}

			iconPath = gatewayUserEntity.getDirPath() + File.separator + "icon" + File.separator
					+ UuidUtil.getInstance().getUUid();
			try {
				// 删除原先头像文件夹
				FileUtils.deleteDirectory(new File(gatewayUserEntity.getIcon()).getParentFile());

				gatewayUserService.fileUpload(icon, iconPath, "");
				iconPath = iconPath + File.separator + icon.getOriginalFilename();
			} catch (IOException e) {
				ExceptionLogger.error(e);
				return super.getFailedRestServiceResult("上传头像失败！");
			}

			params.put("iconPath", iconPath);
			gatewayUserService.modifyUserInfo(params);

			gatewayUserEntity.setIcon("".equals(iconPath) ? gatewayUserEntity.getIcon() : iconPath);

			// 刷新用户缓存
			if (StringUtils.isNotBlank(xypjGatewayToken)) {
				try {
					gatewayAuthenticationService.putUserSessionData(xypjGatewayToken, gatewayUserEntity);
				} catch (Exception e) {
					ExceptionLogger.error(e);
				}
			}
		}

		return super.getSuccessRestServiceResult();
	}

	/**
	 * 获取用户证件照列表
	 *
	 * @param userId
	 *            用户id
	 * @param page
	 *            分页条件
	 * @return
	 */
	@RequestMapping(value = "/getZjPhotoList.json", method = RequestMethod.POST)
	public RestServiceResult getZjPhotoList(
			@RequestParam(value = "userId", defaultValue = "", required = true) String userId, Page page) {
		List<LinkedHashMap> map = gatewayUserService.getZjPhotoListForPage(Long.parseLong(userId), page);
		return super.getPageSuccessRestServiceResult(page.getTotalCount(), map);
	}

	/**
	 * 获取证件照对象
	 *
	 * @param id
	 *            证件照id
	 * @return
	 */
	@RequestMapping(value = "/getZjPhotoInfo.json", method = RequestMethod.POST)
	public RestServiceResult getZjPhotoInfo(@RequestParam(value = "id", defaultValue = "", required = true) String id) {
		return super.getSuccessRestServiceResult(gatewayUserService.getZjPhotoInfo(Long.parseLong(id)));
	}

	/**
	 * 新增证件照
	 *
	 * @param zjName
	 *            证照名称
	 * @param zjdw
	 *            颁发单位
	 * @param type
	 *            证照分类（字典值维护）
	 * @param startTime
	 *            起始日期
	 * @param endTime
	 *            结束日期
	 * @param userId
	 *            用户id
	 * @param file
	 *            文件
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "/addZjPhotoInfo.json", method = RequestMethod.POST)
	public RestServiceResult addZjPhotoInfo(
			@RequestParam(value = "zjName", defaultValue = "", required = true) String zjName,
			@RequestParam(value = "zjdw", defaultValue = "", required = true) String zjdw,
			@RequestParam(value = "type", defaultValue = "", required = true) String type,
			@RequestParam(value = "typeValue", defaultValue = "", required = true) String typeValue,
			@RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
			@RequestParam(value = "endTime", defaultValue = "", required = true) String endTime,
			@RequestParam(value = "userId", defaultValue = "", required = true) String userId,
			@RequestParam(value = "status", defaultValue = "", required = false) String status, MultipartFile file) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", Long.parseLong(userId));
		GatewayUserEntity gatewayUserEntity = gatewayUserService.getUserByTwoPrincipal(params);

		// 上传头像
		String filepath = "";
		if (null == file) {
			return super.getFailedRestServiceResult("请选择证件照！");
		}

		if (!file.getOriginalFilename().toLowerCase().endsWith(".png")
				&& !file.getOriginalFilename().toLowerCase().endsWith(".jpeg")
				&& !file.getOriginalFilename().toLowerCase().endsWith(".jpg")
				&& !file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
			return super.getFailedRestServiceResult("证件照仅支持jpg,jpeg,png,pdf格式");
		}

		if (file.getSize() > 1 * 1024 * 1024) {
			return super.getFailedRestServiceResult("证件照大小超过1M");
		}

		filepath = gatewayUserEntity.getDirPath() + File.separator + "zjphoto" + File.separator
				+ UuidUtil.getInstance().getUUid();
		try {
			gatewayUserService.fileUpload(file, filepath, "");
			filepath = filepath + File.separator + file.getOriginalFilename();
		} catch (IOException e) {
			ExceptionLogger.error(e);
			return super.getFailedRestServiceResult("上传证件照失败！");
		}
		if (status.equals("") || null == status) {
			gatewayUserService.addZjPhotoInfo(zjName, zjdw, type, filepath, startTime, endTime, Long.parseLong(userId),
					typeValue, "1");
		}
		if (status.equals("2")) {
			gatewayUserService.addZjPhotoInfo(zjName, zjdw, type, filepath, startTime, endTime, Long.parseLong(userId),
					typeValue, "2");
		}

		return super.getSuccessRestServiceResult();
	}

	/**
	 * 修改证件照
	 *
	 * @param id
	 *            证件照id
	 * @param zjName
	 *            证照名称
	 * @param zjdw
	 *            颁发单位
	 * @param type
	 *            证照分类（字典值维护）
	 * @param startTime
	 *            起始日期
	 * @param endTime
	 *            结束日期
	 * @param userId
	 *            用户id
	 * @param file
	 *            文件
	 * @return
	 */
	@RequestMapping(value = "/modifyZjPhotoInfo.json", method = RequestMethod.POST)
	public RestServiceResult modifyZjPhotoInfo(
			@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "zjName", defaultValue = "", required = true) String zjName,
			@RequestParam(value = "zjdw", defaultValue = "", required = true) String zjdw,
			@RequestParam(value = "type", defaultValue = "", required = true) String type,
			@RequestParam(value = "typeValue", defaultValue = "", required = true) String typeValue,
			@RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
			@RequestParam(value = "endTime", defaultValue = "", required = true) String endTime,
			@RequestParam(value = "userId", defaultValue = "", required = true) String userId, MultipartFile file) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", Long.parseLong(userId));
		GatewayUserEntity gatewayUserEntity = gatewayUserService.getUserByTwoPrincipal(params);
		LinkedHashMap zjPhotoInfo = gatewayUserService.getZjPhotoInfo(Long.parseLong(id));

		// 上传头像
		String filepath = "";
		if (null != file) {
			if (!file.getOriginalFilename().toLowerCase().endsWith(".png")
					&& !file.getOriginalFilename().toLowerCase().endsWith(".jpeg")
					&& !file.getOriginalFilename().toLowerCase().endsWith(".jpg")
					&& !file.getOriginalFilename().toLowerCase().endsWith(".pdf")) {
				return super.getFailedRestServiceResult("证件照仅支持jpg,jpeg,png,pdf格式");
			}

			if (file.getSize() > 1 * 1024 * 1024) {
				return super.getFailedRestServiceResult("证件照大小超过1M");
			}

			filepath = gatewayUserEntity.getDirPath() + File.separator + "zjphoto" + File.separator
					+ UuidUtil.getInstance().getUUid();
			try {
				// 删除原先头像文件夹
				FileUtils.deleteDirectory(new File((String) zjPhotoInfo.get("filepath")).getParentFile());

				gatewayUserService.fileUpload(file, filepath, "");
				filepath = filepath + File.separator + file.getOriginalFilename();
			} catch (IOException e) {
				ExceptionLogger.error(e);
				return super.getFailedRestServiceResult("上传证件照失败！");
			}
		}

		gatewayUserService.modifyZjPhotoInfo(zjName, zjdw, type, filepath, startTime, endTime, Long.parseLong(id),
				typeValue);
		cardsService.updateCardShzj(id, "3");
		return super.getSuccessRestServiceResult();
	}

	/**
	 * 获取报告历史查询列表
	 *
	 * @param userId
	 *            用户id
	 * @param reportType
	 *            报告类型
	 * @param reportStatus
	 *            报告状态
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @param limit
	 *            一页多少行
	 * @param pageNo
	 *            页数
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/getApplicatonReportList.json", method = RequestMethod.POST)
	public RestServiceResult getApplicatonReportList(
			@RequestParam(value = "userId", defaultValue = "", required = false) String userId,
			@RequestParam(value = "reportType", defaultValue = "", required = false) String reportType,
			@RequestParam(value = "region", defaultValue = "", required = false) String region,
			@RequestParam(value = "industry", defaultValue = "", required = false) String industry,
			@RequestParam(value = "reportStatus", defaultValue = "", required = false) String reportStatus,
			@RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
			@RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
			@RequestParam(value = "limit", defaultValue = "", required = true) String limit,
			@RequestParam(value = "pageNo", defaultValue = "", required = true) String pageNo) {
		Page page = new Page();
		page.setLimit(Integer.parseInt(limit));
		page.setPage(Integer.parseInt(pageNo));
		List<LinkedHashMap> map = gatewayUserService.selectApplicatonReportListForPage(userId, reportType, reportStatus,
				region, industry, startTime, endTime, page);
		return super.getPageSuccessRestServiceResult(page.getTotalCount(), map);
	}

	/**
	 * 删除证件照(物理删除)
	 *
	 * @param id
	 *            证件照id
	 * @return
	 */
	@RequestMapping(value = "/delZjPhotoInfo.json", method = RequestMethod.POST)
	public RestServiceResult delZjPhotoInfo(@RequestParam(value = "id", defaultValue = "", required = true) String id) {
		gatewayUserService.delZjPhotoInfo(Long.parseLong(id));
		return super.getSuccessRestServiceResult();
	}

	/**
	 * 查看报告
	 *
	 * @param id
	 *            用户id
	 * @param bgbh
	 *            报告编号
	 * @return
	 */
	@RequestMapping(value = "/openReport.json")
	public void openReport(@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "bgbh", defaultValue = "", required = true) String bgbh, HttpServletResponse response)
			throws IOException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", Long.parseLong(id));
		GatewayUserEntity gatewayUserEntity = gatewayUserService.getUserByTwoPrincipal(params);

		String path = absolutepath + File.separator + "reports" + File.separator;
		path += bgbh;
		path += File.separator + gatewayUserEntity.getZtmc() + ".pdf";

		response.setContentType("application/pdf");

		ServletOutputStream outputStream = response.getOutputStream();

		response.setHeader("Content-Disposition", "inline;fileName=金电联行(江苏)信息技术有限公司.pdf");

		File pdf = null;
		FileInputStream fis = null;
		byte[] buffer = new byte[1024 * 1024];
		pdf = new File(path);
		response.setContentLength((int) pdf.length());
		fis = new FileInputStream(pdf);
		int readBytes = -1;
		while ((readBytes = fis.read(buffer, 0, 1024 * 1024)) != -1) {
			outputStream.write(buffer, 0, 1024 * 1024);
		}
		outputStream.close();
		fis.close();
	}

	/**
	 * 校验报告是否存在
	 *
	 * @param id
	 *            用户id
	 * @param bgbh
	 *            报告编号
	 * @return
	 */
	@RequestMapping(value = "/checkReport.json")
	public RestServiceResult checkReport(@RequestParam(value = "id", defaultValue = "", required = true) String id,
			@RequestParam(value = "bgbh", defaultValue = "", required = true) String bgbh) throws IOException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", Long.parseLong(id));
		GatewayUserEntity gatewayUserEntity = gatewayUserService.getUserByTwoPrincipal(params);

		String path = absolutepath + File.separator + "reports" + File.separator;
		path += bgbh;
		path += File.separator + gatewayUserEntity.getZtmc() + ".pdf";
		if (org.apache.commons.lang3.StringUtils.isBlank(path) || !(new File(path).exists())) {
			return super.getFailedRestServiceResult("报告已不存在,请联系管理员");
		} else {
			return super.getSuccessRestServiceResult();
		}
	}
}